package com.scs.application.modules.upms.controller;

import com.scs.application.core.mvc.controller.BaseController;
import com.scs.application.modules.upms.service.WxmpAccountService;
import com.scs.application.modules.upms.service.WxmpMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/upms/wx/portal/{mpKey}")
public class WxPortalController extends BaseController {

    private final WxmpAccountService wxmpAccountService;
    private final WxmpMemberService wxmpMemberService;


    private final WxMpService wxMpService;

    /**
     * 检查签名有效性
     *
     * @param mpKey
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @throws IOException
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public void checkSignature(
            @PathVariable("mpKey") String mpKey,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(name = "echostr", required = false) String echostr,
            HttpServletResponse response) throws IOException {
        log.info("接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        response().setHeader("Content-Type", "text/plain;charset=utf-8");

        wxMpService.switchoverTo(mpKey);


        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            response.getWriter().write(echostr);
        } else {
            response.getWriter().write("error");
        }
    }


    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable("mpKey") String mpKey,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {


//        log.info("接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
//                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
//                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);


        if (!this.wxMpService.switchover(mpKey)) {
            throw new IllegalArgumentException(String.format("未找到对应mpKey=[%s]的配置，请核实！", mpKey));
        }

        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }



    private final WxMpMessageRouter messageRouter;

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

}
